package com.rech.xbexpress3;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.dialog.CustomDialog;
import com.rech.utils.OtherUtil;
import com.rech.view.NumberKeyboardView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 微信下单界面
 * Created by sunshine on 2020/9/29
 */
public class Jj3WXActivity extends AppCompatActivity {
    private Timer countTimer;
    private TextView djs;
    private int jjcount = 100;
    private EditText jjm;
    private NumberKeyboardView keyboardView;
    private LinearLayout ll_take;
    private ImageView iv_delete;
    private int jjcount2 = 5;
    private Timer countTimer2;
    private CustomDialog commitDialog;
    private TextView dialog_djs;
    private TextView tv_hint;
    private Button btn_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation", "");
        if (orientation.equals("landscape")) {
            setContentView(R.layout.activity_jj3wx_land);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setContentView(R.layout.activity_jj3wx);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        getSupportActionBar().hide();

        djs = findViewById(R.id.djs);
        jjm = findViewById(R.id.jjm);

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(Jj2Activity.this);
                    Exit();
                    finish();
                }
            }
        },0,1000);

        ImageView gzh_qrcode = (ImageView)findViewById(R.id.gzh_qrcode);
        String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
        new FetchUrlImageTask(cnImage,gzh_qrcode).execute();

        ll_take = (LinearLayout) findViewById(R.id.ll_take);
        keyboardView = new NumberKeyboardView(this, false);
        ll_take.addView(keyboardView);
        //keyboardView = (NumberKeyboardView) findViewById(R.id.keyboardView);
        final Button tv_one = keyboardView.findViewById(R.id.one);
        final Button tv_two = keyboardView.findViewById(R.id.two);
        final Button tv_three = keyboardView.findViewById(R.id.three);
        final Button tv_four = keyboardView.findViewById(R.id.four);
        final Button tv_five = keyboardView.findViewById(R.id.five);
        final Button tv_six = keyboardView.findViewById(R.id.six);
        final Button tv_seven = keyboardView.findViewById(R.id.seven);
        final Button tv_eight = keyboardView.findViewById(R.id.eight);
        final Button tv_nine = keyboardView.findViewById(R.id.nine);
        final Button tv_zero = keyboardView.findViewById(R.id.zero);
        final Button tv_confirm = keyboardView.findViewById(R.id.confirm);
        final Button tv_cancel = keyboardView.findViewById(R.id.cancel);
        final Button tv_delete = keyboardView.findViewById(R.id.delete);
        tv_zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_zero);
            }
        });

        tv_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_one);
            }
        });

        tv_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_two);
            }
        });

        tv_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_three);
            }
        });

        tv_four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_four);
            }
        });

        tv_five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_five);
            }
        });

        tv_six.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_six);
            }
        });

        tv_seven.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_seven);
            }
        });

        tv_eight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_eight);
            }
        });

        tv_nine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_nine);
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Exit();
                finish();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new PostByCodeTask(jjm.getText().toString().trim()).execute();
            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String editextStr = jjm.getText().toString().trim();
                if (editextStr.length() > 0) {
                    jjm.setText(editextStr.substring(0, editextStr.length() - 1));
                }
                cursorLast(jjm);
            }
        });


        iv_delete = (ImageView) findViewById(R.id.iv_delete);
        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jjm.setText("");
            }
        });

        hideSoftInputMethod(jjm);
        //jjm.setFocusableInTouchMode(false);
        jjm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() > 0) {
                    jjm.setHeight(OtherUtil.dp2px(120));
                    jjm.setBackgroundResource(R.mipmap.editext_background_active);
                    iv_delete.setVisibility(View.VISIBLE);
                } else {
                    jjm.setHeight(OtherUtil.dp2px(90));
                    jjm.setBackgroundResource(R.drawable.bg_blue_button_stroke);
                    iv_delete.setVisibility(View.GONE);
                }

                if (editable.toString().trim().length() == 6) {
                    new PostByCodeTask(editable.toString().trim()).execute();
                }
            }
        });

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);

        TextView tv_back = findViewById(R.id.tv_back);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(1001, intent);
                Exit();
                finish();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10205:
                Toast.makeText(Jj3WXActivity.this, "寄件失败请重试", Toast.LENGTH_SHORT).show();
                jjm.setText("");
                break;
            case 10204:
                handleJJTask(message.obj);
                jjm.setText("");
                break;
            case 20000:
                handleDJS();
                break;
            case 20001:
                handleDJS2();
                break;
        }
    }

    private void handleDJS2(){
        dialog_djs.setText(jjcount2 + "");
    }

    private void handleJJTask(Object  obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("jj_sjr_address",result.getJSONObject("data").getString("receiver"));
                editor.putString("jj_jjr_address",result.getJSONObject("data").getString("sender"));
                editor.putString("jj_wx_orderId",result.getJSONObject("data").getString("orderId"));

                int mExpType = 0;
                editor.putInt("jj_exp",mExpType);
                //editor.putString("jj_boxvalue",boxValue);
                editor.apply();
                Intent intent = new Intent();
                intent.putExtra("isFromWX", true);
                setResult(1002, intent);
                Exit();
                finish();
            }else{

                /*View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle("寄件码错误，请重新输入");
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);*/

                showFailDialog();
            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }

    private void showFailDialog() {
        View view = View.inflate(this, R.layout.dialog_fail, null);
        initDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(500), OtherUtil.dp2px(560),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initDialogView(View view) {
        jjcount2 = 5;
        dialog_djs = view.findViewById(R.id.tv_djs);
        btn_confirm = view.findViewById(R.id.btn_confirm);
        tv_hint = view.findViewById(R.id.tv_hint);
        dialog_djs.setText(jjcount2 + "");
        tv_hint.setText("寄件码错误");

        countTimer2=new Timer();
        countTimer2.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount2--;
                Message message = new Message();
                message.what=20001;
                EventBus.getDefault().post(message);
                if(jjcount2 < 1){
                    closeDialog();
                    countTimer2.cancel();
                }
            }
        },0,1000);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }

    private void Exit(){
        countTimer.cancel();
        EventBus.getDefault().unregister(this);
    }

    private void inputAppendData(Button tv_one) {
        String a = jjm.getText().toString().trim();
        String b = tv_one.getText().toString().trim();
        jjm.setText(a + b);
        //光标显示到最后
        cursorLast(jjm);
    }

    private void cursorLast(EditText idEdit) {
        Editable etext = idEdit.getText();
        Selection.setSelection(etext, etext.length());
    }

    private void hideSoftInputMethod(EditText ed) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        int currentVersion = android.os.Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }

        if (methodName == null) {
            ed.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(ed, false);
            } catch (NoSuchMethodException e) {
                ed.setInputType(InputType.TYPE_NULL);
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}
